<template>
  <a-upload
    :show-file-list="false"
    :custom-request="customRequest"
    @success="handleSuccess"
    @error="handleError"
  >
    <template #upload-button>
      <div
        :class="`arco-upload-list-item !m-0${
          file && file.status === 'error' ? ' arco-upload-list-item-error' : ''
        }`"
      >
        <slot></slot>
      </div>
    </template>
  </a-upload>
</template>

<script setup>
import { ref } from 'vue'
import { getToken } from '@/utils/auth'
import { Message } from '@arco-design/web-vue'
const emits = defineEmits(['update:fileUrl', 'success'])
const file = ref()

const handleError = () => {
  Message.error('上传失败')
}
const handleSuccess = ({ response }) => {
  const res = JSON.parse(response)
  if (res.code === 200) {
    const data = res.data.file
    Message.success('上传成功')

    emits('success', data.url)
  } else {
    Message.error('上传失败')
  }
}
const customRequest = (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option
  const xhr = new XMLHttpRequest()
  if (xhr.upload) {
    xhr.upload.onprogress = (event) => {
      let percent = 0
      if (event.total > 0) {
        // 0 ~ 1
        percent = event.loaded / event.total
      }
      onProgress(percent, event)
    }
  }
  xhr.onerror = function error(e) {
    onError(e)
  }
  xhr.onload = function onload() {
    if (xhr.status < 200 || xhr.status >= 300) {
      return onError(xhr.responseText)
    }
    return onSuccess(xhr.response)
  }

  const formData = new FormData()
  formData.append(name || 'file', fileItem.file)
  xhr.open('post', '/api/fileUploadAndDownload/upload', true)
  xhr.setRequestHeader('x-token', getToken())
  xhr.send(formData)

  return {
    abort() {
      xhr.abort()
    }
  }
}
</script>
